﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Validation;
using System.Linq;
using System.Transactions;
using System.Web;

using System.Data;
using EPanShareSystem.Model;


namespace EPanShareSystem.DbUtity
{

    //

    /// <summary>
    /// EF数据库访问类（net4.0）
    /// </summary>
    public class EFDbHelper
    {
        Entities db = new Entities();
        /// <summary>
        /// 添加实体
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public T Add<T>(T entity) where T : class
        {
            var model = db.Set<T>().Add(entity);
            return db.SaveChanges() > 0 ? model : null;
        }

        /// <summary>
        /// 修改记录
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public bool Update<T>(T entity) where T : class
        {
            db.Entry(entity).State = EntityState.Modified;
            return db.SaveChanges() > 0 ? true : false;
        }

        /// <summary>
        /// 删除记录
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public bool Delete<T>(T entity) where T : class
        {
            db.Entry(entity).State = EntityState.Deleted;
            return db.SaveChanges() > 0 ? true : false;
        }

        /// <summary>
        /// 查询实体
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        public T Find<T>(object key) where T : class
        {
            return db.Set<T>().Find(key);
        }


        public T Find<T>(Func<T, bool> whereLambda) where T : class
        {
            var obj = db.Set<T>().Where(whereLambda);
            if (obj != null && obj.Count() > 0)
            {
                return obj.First();
            }
            else
            {
                return null;
            }
        }

        public T Find<T>(string sql, params object[] parameters) where T : class
        {
            // db.Set<T>().Where(sql,parameters).s
            return db.Database.SqlQuery<T>(sql, parameters).SingleOrDefault<T>();
        }


        public IEnumerable<T> FinList<T>(Func<T, bool> whereLambda) where T : class
        {
            return db.Set<T>().Where(whereLambda);
        }
        public IEnumerable<T> FinList<T>(string sql, params object[] parameters) where T : class
        {
            return db.Database.SqlQuery<T>(sql, parameters);
        }
        public IEnumerable<T> FinList<T>(string sql) where T : class
        {
            return db.Database.SqlQuery<T>(sql);
        }

        /// <summary>
        /// 查询返回DataTable
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="sql"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        //public DataTable FindList<T>(string sql, params object[] parameters) where T : class
        //{
        //    var list = db.Database.SqlQuery<T>(sql, parameters).ToList();
        //    var dt = Utils.ToDataTable(list);
        //    return dt;
        //}
        public IEnumerable<T> FindAllList<T>() where T : class
        {
            return db.Set<T>();
        }

        /// <summary>
        /// 查询存储过程
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="sql"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public T FindQueryWithProcedure<T>(string sql, params object[] parameters) where T : class
        {
            // db.Set<T>().Where(sql,parameters).s
            return db.Database.SqlQuery<T>(sql, parameters).SingleOrDefault<T>();
        }
        /// <summary>
        /// EF带事务操作
        /// </summary>
        /// <param name="dataList"></param>
        /// <returns></returns>
        public bool BatchOperation(List<SaveEntityModel> dataList)
        {
            using (var transaction = new TransactionScope())
            {
                db.Configuration.AutoDetectChangesEnabled = false;
                try
                {
                    foreach (SaveEntityModel item in dataList)
                    {
                        var entry = db.Entry(item.Entity);
                        //if (item.State == EntityState.Modified && !string.IsNullOrEmpty(item.UpdateFields))
                        //{
                        //    item.State = EntityState.Unchanged;
                        //    item.UpdateFields.Split(',').ToList().ForEach(f =>
                        //    {
                        //        entry.Property(f).IsModified = true;
                        //    });
                        //}
                        entry.State = item.State;
                    }
                    db.SaveChanges();
                    transaction.Complete();
                    return true;
                }
                catch (DbEntityValidationException exx)
                {
                    // var aa=  exx.EntityValidationErrors.ElementAt(0);
                    throw exx;
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    db.Configuration.AutoDetectChangesEnabled = true;
                    //transaction.Dispose();
                }
            }
        }




    }

    public class SaveEntityModel
    {
        public EntityState State { get; set; }

        public object Entity { get; set; }

        //public string UpdateFields { get; set; }

    }
}